package com.stms.action;

import com.alibaba.fastjson.JSONObject;
import com.stms.utils.Result;
import com.stms.pojo.Contract;
import com.stms.service.ContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@CrossOrigin
@RestController
@RequestMapping("/contract")
public class ContractController {
    @Autowired
    public ContractService contractService;

    private Integer count;

    @PostMapping("/addContract")
    public Result addContract(@RequestBody Contract contract){
        boolean flag = contractService.addContract(contract);
        if(flag){
            return new Result(200,"add success");
        }else {
            return new Result(500,"add fail");
        }
    }

    @PostMapping("/editContract")
    public Result editContract(@RequestBody Contract contract){
        boolean flag = contractService.editContract(contract);
        if(flag){
            return new Result(200,"edit success");
        }else {
            return new Result(500,"edit fail");
        }
    }

    @PostMapping("/deleteContract")
    public Result deleteContract(@RequestBody JSONObject obj){
        try{
            String contractIds = (String)obj.get("contractIds");
            contractService.deleteBatch(contractIds);
            return new Result(200,"delete success");
        }catch(Exception e){
            e.printStackTrace();
            return new Result(500,"error");
        }
    }

    @PostMapping("/fuzzyQuery")
    public Map fuzzyQuery(Integer pageNum,Integer pageSize,String direction, Contract contract){
        Page<Contract> page = contractService.fuzzyQuery(pageNum,pageSize,direction,contract);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("data",page);
        return map;
    }

    @PostMapping("/findByPage")
    public Map findByPage(Integer pageNum,Integer pageSize){
        if(count!=null&&pageNum>=count){
            pageNum=count;
        }

        Page<Contract> page = contractService.findByPage(pageNum,pageSize);
        count = page.getTotalPages();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("data",page);
        return map;
    }
}
